package com.better517na.elasticseach.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class ESUtils {
    public static String[] getHits(String resource){
        JSONObject resourceObj = JSONObject.parseObject(resource);
        JSONObject hitsObj = JSONObject.parseObject(resourceObj.getString("hits"));
        JSONArray hits = JSONObject.parseArray(hitsObj.getString("hits"));
        String[] result = new String[hits.size()];
        for (int i = 0 ; i < hits.size(); i++){
            JSONObject hitObj = hits.getJSONObject(i);
            String source = hitObj.getString("_source");
            result[i] = source;
        }
        return result;
    }

    public static Map<String, String> getHitsWithID(String resource){
        Map<String, String> result = new HashMap<String, String>();
        JSONObject resourceObj = JSONObject.parseObject(resource);
        JSONObject hitsObj = JSONObject.parseObject(resourceObj.getString("hits"));
        JSONArray hits = JSONObject.parseArray(hitsObj.getString("hits"));

        for (int i = 0 ; i < hits.size(); i++){
            JSONObject hitObj = hits.getJSONObject(i);
            String source = hitObj.getString("_source");
            String id = hitObj.getString("_id");
            result.put(id,source);
        }
        return result;
    }
}
